/**
 * Obj模型类
 * @param {WebGL Object} gl WebGL对象
 * @param {Array} vertexData 顶点坐标数据
 * @param {Array} textureData 纹理坐标数据
 * @param {Texture Object} texture 纹理对象
 */
function ObjObject(gl, vertexData=[], textureData=[], texture=null){
    this.gl = gl;
    this.vertexData = vertexData;
    this.vertexCount = vertexData.length/3;
    this.textureData = textureData;
    this.texture = texture;
    // 绑定顶点缓冲数据
    this.vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.vertexData), gl.STATIC_DRAW);

    // 绑定纹理缓冲数据
    this.textureBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.textureData), gl.STATIC_DRAW);
}
ObjObject.prototype.drawSelf = function(ms){
    var gl = this.gl;
    
    // 绑定顶点数据
    var vertexPosition = gl.getAttribLocation(gl.program, "aPosition");
    if(vertexPosition<0){
        throw new Error("aPosition属性未找到!");
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
    gl.vertexAttribPointer(vertexPosition, 3, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(vertexPosition);

    // 绑定纹理数据
    var texturePosition = gl.getAttribLocation(gl.program, "aTexCoor");
    if(texturePosition<0){
        throw new Error("aPosition属性未找到!");
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
    gl.vertexAttribPointer(texturePosition, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(texturePosition);

    // 绑定纹理
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, this.texture);
    gl.uniform1i(gl.getUniformLocation(gl.program, "sTexture"), 0);

    // 绑定变换矩阵
    var uMVPMatrixPosition=gl.getUniformLocation(gl.program, "uMVPMatrix");
    if(uMVPMatrixPosition<0){
        throw new Error("uMVPMatrix属性未找到!");
    }
    gl.uniformMatrix4fv(uMVPMatrixPosition,false,new Float32Array(ms.getFinalMatrix())); 
    
    // 绘制
    ms.pushMatrix();
    gl.drawArrays(gl.TRIANGLES,0,this.vertexCount);
    ms.popMatrix();
}

export { ObjObject };